package com.uchedao.ulibrary.fragment;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.uchedao.ulibrary.R;

/**
 * Fragment管理器
 * */
public class FragmentMrg {

	private static final String TAG = "comveefrag";

	/**
	 * 前往fragment
	 *
	 * @param activity
	 *            父Activity
	 * @param frag
	 *            目标fragment
	 * @param canBack
	 *            是否可以返回到当前页面，清空堆栈
	 * @param anim
	 *            动画
	 * */
	public static final void toFragment(FragmentActivity activity,
			Fragment frag, boolean canBack, boolean anim) {
		System.gc();
		try {
			FragmentManager mrg = activity.getSupportFragmentManager();
			FragmentTransaction mTran = mrg.beginTransaction();
			if (anim) {
				mTran.setCustomAnimations(R.anim.push_left_in,
						R.anim.push_left_out, R.anim.push_right_in,
						R.anim.push_right_out);
			}
			mTran.replace(R.id.frag_content, frag, TAG);
			if (canBack) {
				mTran.addToBackStack(null);
			}
			mTran.commit();
			mrg.executePendingTransactions();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 移除堆栈中的目标fragment
	 * */
	public static final void toBack(Fragment fragment) {
		fragment.getFragmentManager().popBackStack();
		fragment.getFragmentManager().beginTransaction().remove(fragment)
				.commit();
	}

	/**
	 * 返回键响应事件
	 * */
	public static final boolean onKeyBack(FragmentActivity activity) {
		final BaseFragment frag = ((BaseFragment) activity
				.getSupportFragmentManager().findFragmentByTag(TAG));
		if (frag == null) {
			return false;
		} else if (frag.onBackPress()) {
			return true;
		} else {
			toBack(frag);
			return true;
		}
	}
}
